//
//  programmeviewcontroller.m
//  Prospectus
//
//  Created by Ken Power on 28/01/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "programmeviewcontroller.h"
#import "Programme.h"
#import <Foundation/NSCharacterSet.h>


@implementation ProgrammeViewController

@synthesize programme;
//UILables
@synthesize maintitle;
@synthesize subtitle;
@synthesize pointsCutOff;
@synthesize numYears;
@synthesize numPlaces;
//UIButton
@synthesize aboutThisProgramme;
@synthesize careerOptions;
@synthesize followOnStudy;
@synthesize specialFeatures;
@synthesize exemptions;
@synthesize contact;
@synthesize subjectsStudied;
@synthesize entryRequirements;
@synthesize grants;
@synthesize txtPointsCutOff;
@synthesize txtNumPlaces;
@synthesize txtDuration;


@synthesize details;




- (void)viewDidLoad{
	[super viewDidLoad];
	
	//UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction
	//																		   target:self action:nil];    
	//self.navigationItem.rightBarButtonItem = addButton;
	//[addButton release];
 
	NSMutableString *navTitle=[NSMutableString  stringWithString:@"Course code: "];
	[navTitle appendString:self.programme.CAOCode];

	self.navigationItem.title=navTitle;
	

	
	NSMutableString *subTitle=[NSMutableString  stringWithString:[self.programme CAOCode]];
	[subTitle appendString:@" "];
	[subTitle appendString:[self.programme AwardType]];
	[subTitle appendString:@" in"];
	
	[subtitle setText:subTitle];
	[maintitle setText:[self.programme Title]];
	
	btnCurrentTab=aboutThisProgramme; // this is startup active tab
	

	[details loadHTMLString:[self GetOverViewHTML]  
						baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
	
}

-(IBAction)buttonPress:sender{
	UIButton* btn=(UIButton*)sender;
	NSString* detailsHTML;
	
	if (btn==aboutThisProgramme) {
		detailsHTML=[self GetOverViewHTML ];

	}
	else if (btn==careerOptions) {
		//[details loadHTMLString:[programme TextAbleToDo] baseURL:nil];
		detailsHTML=[self GetCareerHTML ];
	}
	
	else if (btn==entryRequirements) {
		//[details loadHTMLString:[programme TextAbleToDo] baseURL:nil];
		detailsHTML=[self GetEntryHTML ];
	}
	
	
	else if (btn==specialFeatures) {
		//[details loadHTMLString:[programme TextSpecialFeatures] baseURL:nil];
		detailsHTML=[self GetFeaturesHTML ];
	}
	
	else if (btn==subjectsStudied) {
		//[details loadHTMLString:[self GetSubjectList] baseURL:nil];
		detailsHTML=[self GetSubjectHTML ];
	}
	
	else
		return;

	//detailsHTML=@"<html><head></head><body><p>test</p></body></html>";
	[details loadHTMLString:detailsHTML  baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
	
	UIImage *whitetab=[btnCurrentTab backgroundImageForState:UIControlStateNormal]; //should be active(white) tab
	UIImage *greytab=[btn backgroundImageForState:UIControlStateNormal]; //should be inactive grey tab
	
	[btnCurrentTab setBackgroundImage:greytab forState:UIControlStateNormal];
	
	[btn setBackgroundImage:whitetab forState:UIControlStateNormal];
	
	btnCurrentTab=btn;
	
}
	
	 
-(NSString*)GetSubjectHTML{
	
//	NSMutableString *html=[NSMutableString  stringWithString:@"<HTML><HEAD>\
//						   <LINK href=\"style.css\" rel=\"stylesheet\" type=\"text/css\">\
//						   </HEAD>\
//						   <BODY class=\"subjects\"><h1>Subjects Studied</h1>"];
//						   
//	NSString* tail=@"</body></HTML>";
		
	NSMutableString *html=[[NSMutableString alloc] init];
	if ([[self.programme SubjectsYear1] compare:@""]!=0) {
		
		[html appendString:@"<h2>Year 1</h2>"];
		[html appendString:[self GetHTMLSubjectsForYear:[programme SubjectsYear1]]];		
		   
	}

	if ([[self.programme SubjectsYear2] compare:@""]!=0) {
			 
		[html appendString:@"<h2>Year 2</h2>"];
		[html appendString:[self GetHTMLSubjectsForYear:[programme SubjectsYear2]]];		
			  
	}
	if ([[self.programme SubjectsYear3] compare:@""]!=0) {
				  
		[html appendString:@"<h2 >Year 3</h2>"];
		[html appendString:[self GetHTMLSubjectsForYear:[programme SubjectsYear3]]];		
					
	}
	if ([[self.programme SubjectsYear4] compare:@""]!=0) {
					   
		[html appendString:@"<h2>Year 4</h2>"];
		[html appendString:[self GetHTMLSubjectsForYear:[programme SubjectsYear4]]];		
						
	}

	//[html appendString:tail];

	return [self MakeHTMLPage:html bodyclass:@"subjects"];
																								   
}	

-(NSString*)GetHTMLListOfSubjects:(NSArray*)subjects{
	
	NSMutableString* html=[NSMutableString stringWithString:@"<ol>"];
	
	

	for (NSString* sub in subjects) {

		if ([sub compare:@""]!=0) {
			[html appendString:@"<li>"];
			[html appendString:sub];
			[html appendString:@"</li>"];
		}
	}
	[html appendString:@"</ol>"];
			 
	return html;
			 
}


-(NSString*)GetHTMLSubjectsForYear:(NSString*)subjectList{
	
	NSMutableString *html=[[[NSMutableString alloc] init] autorelease];
	NSArray* mand_elect= [subjectList componentsSeparatedByString:@"$"]; //split into mandatory and elective substrings
	
	NSArray *subjects = [[mand_elect objectAtIndex:0] componentsSeparatedByString:@";"];//create array of mandatory subjects
	
	if ([mand_elect count]>1) {
		[html appendString:@"<h3>Mandatory Subjects</h3>"];
	}
	
	[html appendString:[self GetHTMLListOfSubjects:subjects]];
	
	
	if ([mand_elect count]==2) { //are there elective subjects?
		NSMutableArray *subjects =  [[[mand_elect objectAtIndex:1] componentsSeparatedByString:@";"] mutableCopy];
		
		NSString* first = [subjects objectAtIndex:0];
		
		if ([first length]==1) { //check if the first line of the elective section is a digit
			[html appendString:@"<h4>Plus "];
			if ([first compare:@"1"]==0) {
				[html appendString:@"one elective:</h4>"];
			}
			else {
				[html appendString:[subjects objectAtIndex:0]];
				[html appendString:@" electives:</h4>"];
			}
			
			[subjects removeObjectAtIndex:0];
			
			
		}
		
		[html appendString:[self GetHTMLListOfSubjects:subjects]];
		
		
		
	}
	return html;
	
}



-(NSString*)GetOverViewHTML{
	
	NSMutableString *html=[NSMutableString  stringWithString:@"<h1>%code% %awardtype% in <br/>%title%</h1>\
						   <p class=\"info\">CAO cut-off 2010: %CAOpoints%points</p>\
						   <p class=\"info\">%Numplaces% places available</p>\
						   <p class=\"info\">Duration: %Duration% years</p>%image%<p>%body%</p>"];
	
	[html replaceOccurrencesOfString:@"%code%" withString:[programme CAOCode] options:0 range: NSMakeRange(0, [html length])];
	[html replaceOccurrencesOfString:@"%awardtype%" withString:[programme AwardType] options:0 range: NSMakeRange(0, [html length])];
	[html replaceOccurrencesOfString:@"%title%" withString:[programme Title] options:0 range: NSMakeRange(0, [html length])];

	[html replaceOccurrencesOfString:@"%CAOpoints%" 
						  withString:[NSString stringWithFormat:@"%d", [programme PointsCutOff]] 
							 options:0 range: NSMakeRange(0, [html length])];

	[html replaceOccurrencesOfString:@"%Numplaces%" 
						  withString:[NSString stringWithFormat:@"%d", [programme NumPlaces]] 
							 options:0 range: NSMakeRange(0, [html length])];

	[html replaceOccurrencesOfString:@"%Duration%" 
						  withString:[NSString stringWithFormat:@"%d", [programme NumYears]] 
							 options:0 range: NSMakeRange(0, [html length])];
	
	
	
	[html replaceOccurrencesOfString:@"%body%" withString:[programme TextWhatCourseIsAbout] options:0 range: NSMakeRange(0, [html length])];
	
	NSMutableString* image =[NSMutableString stringWithString:@"<div align=\"center\"><img src=\"%imagename%.png\" width=\"200px\"/></div>"];
								 
	[image replaceOccurrencesOfString:@"%imagename%" withString:[programme CAOCode] options:0 range: NSMakeRange(0, [image length])];
	
	[html replaceOccurrencesOfString:@"%image%" withString:image options:0 range: NSMakeRange(0, [html length])];
	
	return [self MakeHTMLPage:html bodyclass:@"overview"];
	
	
}

-(NSString*)GetFeaturesHTML{
	
	NSMutableString *html=[NSMutableString stringWithString:@"<h1>%title%</h1><p>%body%</p>"];

	
	[html replaceOccurrencesOfString:@"%title%" withString:NSLocalizedString(@"SpecialFeaturesOfThisCourse",nil) options:0 range: NSMakeRange(0, [html length])];
	
	if([[self.programme TextSpecialFeatures]  compare:@""]==0)	
	{
		NSString* genericFeatures=@"<p>Our courses are designed to meet the specific needs of the industrial and commercial sectors and include a wide range of Honours Degree courses in a broad range of disciplines. The facilities at IT Carlow include a state-of-the-art Learning Resource Centre with over 1,200 learner stations, purpose-built laboratories, workshops and studios.</p>";
		[html replaceOccurrencesOfString:@"%body%" withString:genericFeatures options:0 range: NSMakeRange(0, [html length])];

	}
	else {
		[html replaceOccurrencesOfString:@"%body%" withString:[programme TextSpecialFeatures] options:0 range: NSMakeRange(0, [html length])];

	}

	
	
	return [self MakeHTMLPage:html bodyclass:@"features"];
	
	
}
	 

	 
	 
-(NSString*)GetCareerHTML{
		 
	NSMutableString *html=[NSMutableString stringWithString:@""];
	
		 
	if([programme TextAbleToDo] !=nil){
		[html appendString:@"<h1>%FollowOn%</h1><p>%follow%</p>"];
		[html replaceOccurrencesOfString:@"%FollowOn%" withString:NSLocalizedString(@"FollowOnOptions",nil) options:0 range: NSMakeRange(0, [html length])];
		[html replaceOccurrencesOfString:@"%follow%" withString:[programme TextAbleToDo] options:0 range: NSMakeRange(0, [html length])];
	}
	if([programme TextFollowOnOppertunities] !=nil){
		[html appendString:@"<h1>%CareerOppertunities%</h1><p>%career%</p>"];
		[html replaceOccurrencesOfString:@"%CareerOppertunities%" withString:NSLocalizedString(@"CareerOppertunities",nil) options:0 range: NSMakeRange(0, [html length])];
		[html replaceOccurrencesOfString:@"%career%" withString:[programme TextFollowOnOppertunities] options:0 range: NSMakeRange(0, [html length])];
		 }
	if([programme TextExemptionsAvailable] !=nil){
		[html appendString:@"<h1>%ProfessionalExemptions%</h1><p>%exemptions%</p>"];
		[html replaceOccurrencesOfString:@"%ProfessionalExemptions%" withString:NSLocalizedString(@"ProfessionalExemptions",nil) options:0 range: NSMakeRange(0, [html length])];		
		[html replaceOccurrencesOfString:@"%exemptions%" withString:[programme TextExemptionsAvailable] options:0 range: NSMakeRange(0, [html length])];
	}
		 
	return [self MakeHTMLPage:html bodyclass:@"career"];

		 
	 }

-(NSString*)GetEntryHTML{
	
	NSMutableString *html=[NSMutableString stringWithString:@""];
	
	if([programme TextMinimumEntryRequirements] !=nil){
		[html appendString:@"<h1>Minimum Entry Requirements</h1><p>%entry%</p>"];
		[html replaceOccurrencesOfString:@"%entry%" withString:[programme TextMinimumEntryRequirements] options:0 range: NSMakeRange(0, [html length])];
	}
	
	
	return [self MakeHTMLPage:html bodyclass:@"entry"];
	
}

-(NSString*)MakeHTMLPage:(NSString*)body bodyclass:(NSString*)classname{
	
	NSMutableString *html=[NSMutableString  stringWithString:@"<html><head>\
						   <LINK href=\"style.css\" rel=\"stylesheet\" type=\"text/css\">\
						   </head><body class=\"%classname%\"><div id=\"body\">"];// "body" div is used to determine height of webview in webviewdidfinishedloading

	//set the html body class to allow appropriate CSS for each tab
	[html replaceOccurrencesOfString:@"%classname%" withString:classname options:0 range: NSMakeRange(0, [html length])];

	
	[html appendString:body];
	
	[html appendString:@"</div></body></html>"];
						   
	return html;
}

-(void)webViewDidFinishLoad:(UIWebView *)webView{
	if (webView!=details)return;
	
	float h;
	
	NSLog(@"web view is %f high", details.frame.size.height);
	NSString *heightString = [details stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"body\").offsetHeight;"];
	NSLog(@"web content is %@ high",heightString);
	
	h = [heightString floatValue] +12.0f; // convert from string to float plus some extra points because calculation is sometimes one line short
	
	int minheight= [self view].frame.size.height -details.frame.origin.y;
	if(h<minheight){
		h=minheight;// force webview to fill remaining part of screen
	}
	details.frame = CGRectMake(details.frame.origin.x, details.frame.origin.y, details.frame.size.width, h);
	
	// get bottom of text field
	h = details.frame.origin.y + h;
	
	[((UIScrollView*)[self view]) setContentSize:CGSizeMake(320, h)];
	

	
}


- (void)dealloc {
	details.delegate=nil;
	[details release];
	[programme release];
    [super dealloc];
}


@end
